import os
import random
import string

from flask import render_template, g, request, jsonify, session, redirect, url_for

from models import db
from models.index import User, Areas, ShopAddress, Order, Collect, Product
from utils.img_qiniu import upload_image_to_qiniu
from views import user_bp


@user_bp.route('/user_center')
def user_center():
    user = g.user
    if user:
        user_order_list = db.session.query(Order).filter(Order.user_id == user.id).order_by(-Order.order_date).all()
        return render_template('user.html', user=user, user_order_list=user_order_list, shop_car_count=g.shop_car_count)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/user_info', methods=['POST', 'GET'])
def user_info():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == 'GET':
        return render_template('user_info.html', user=user, shop_car_count=g.shop_car_count)
    if request.method == 'POST':
        username = request.json.get('username')
        truename = request.json.get('truename')
        gender = request.json.get('gender')
        phone = request.json.get('phone')
        email = request.json.get('email')

        user_all_list = db.session.query(User).all()
        if len(phone) != 11 and phone != '':
            ret = {
                'errno': 6003,
                'errmsg': '请输入正确的手机号'
            }
            return jsonify(ret)

        if phone in [x.phone for x in user_all_list if x.phone != user.phone]:
            ret = {
                'errno': 6001,
                'errmsg': '手机号码已经存在'
            }
            return jsonify(ret)

        if email in [x.email for x in user_all_list if x.email != user.email]:
            ret = {
                'errno': 6002,
                'errmsg': '邮箱已经存在'
            }
            return jsonify(ret)

        if phone == '':
            phone = user.phone
        if email == '':
            email = user.email

        user.nick_name = username
        user.truth_name = truename
        user.gender = gender
        user.phone = phone
        user.email = email
        db.session.add(user)
        db.session.commit()

        ret = {
            'errno': 0,
            'errmsg': '成功'
        }
        return jsonify(ret)


@user_bp.route('/update_psw', methods=['GET', 'POST'])
def update_psw():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == 'GET':
        return render_template('user_Password.html', user=user, shop_car_count=g.shop_car_count)
    else:
        old_psw = request.json.get('old_psw')
        new_psw = request.json.get('new_psw')
        if user.password_hash == old_psw:
            user.password_hash = new_psw
            db.session.add(user)
            db.session.commit()
            session.clear()
            ret = {
                'errno': 0,
                'errmsg': '成功'
            }
        else:
            ret = {
                'errno': 6004,
                'errmsg': '原密码不正确!'
            }

        return jsonify(ret)


@user_bp.route('/address')
def address():
    user = g.user
    if user:
        sheng_list = db.session.query(Areas).filter(Areas.pid == None).all()
        shop_address = user.shop_address

        return render_template('user_address.html', user=user, sheng_list=sheng_list, shop_address=shop_address,
                               shop_car_count=g.shop_car_count)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/select_city', methods=['POST'])
def select_city():
    user = g.user
    if user:
        aid = request.json.get('aid')
        city_list = db.session.query(Areas).filter(Areas.pid == aid).all()
        city_info_list = []
        for i in city_list:
            city_obj = i.__dict__
            del city_obj['_sa_instance_state']
            city_info_list.append(city_obj)
        if city_info_list == []:
            ret = {
                'errno': 6005,
                'errmsg': '没有找到数据',
                'city_info_list': city_info_list
            }
        else:

            ret = {
                'errno': 0,
                'errmsg': '成功',
                'city_info_list': city_info_list
            }
        return jsonify(ret)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/add_address', methods=['POST'])
def add_address():
    user = g.user
    if user:
        user_name = request.json.get('user_name')
        like_address = request.json.get('like_address')
        address = request.json.get('address')
        phone = request.json.get('phone')

        shop_address = ShopAddress()
        shop_address.name = user_name
        shop_address.like_address = like_address
        shop_address.address = address
        shop_address.phone = phone
        shop_address.user_id = user.id
        db.session.add(shop_address)
        db.session.commit()

        ret = {
            'errno': 0,
            'errmsg': '成功'
        }
        return jsonify(ret)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/rm_addr', methods=['POST'])
def rm_addr():
    user = g.user
    if user:
        addr_id = request.json.get('addr_id')
        current_addr = db.session.query(ShopAddress).filter(ShopAddress.id == addr_id,
                                                            ShopAddress.user_id == user.id).first()
        if current_addr:
            db.session.delete(current_addr)
            db.session.commit()
            ret = {
                'errno': 0,
                'errmsg': '删除成功'
            }
        else:
            ret = {
                'errno': 6006,
                'errmsg': '没有找到当前收货地址'
            }
        return jsonify(ret)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/collect_tmp')
def collect_tmp():
    user = g.user
    if user:
        collect_product_info_list = []
        collect_product_list = db.session.query(Collect).filter(Collect.collect_user == user.id).all()
        for collect_product in collect_product_list:
            product_info = db.session.query(Product).filter(Product.id == collect_product.collect_product).first()
            collect_product_info_list.append(product_info)
        return render_template('user_Collect.html', collect_product_info_list=collect_product_info_list, user=user,
                               shop_car_count=g.shop_car_count)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/collect', methods=['POST'])
def collect():
    user = g.user
    if user:

        status = request.json.get('status')
        if status == 'do':
            product_id = request.json.get('product_id')
            if product_id:
                is_collect = db.session.query(Collect).filter(Collect.collect_user == user.id,
                                                              Collect.collect_product == product_id).first()
                if not is_collect:
                    collect_info = Collect()
                    collect_info.collect_user = user.id
                    collect_info.collect_product = product_id
                    db.session.add(collect_info)
                    db.session.commit()
                    ret = {
                        'errno': 0,
                        'errmsg': '收藏成功'
                    }
                else:
                    ret = {
                        'errno': 6007,
                        'errmsg': '已经收藏了该商品'
                    }

            else:
                ret = {
                    'errno': 6008,
                    'errmsg': '没有要收藏的商品'
                }
            return jsonify(ret)
        elif status == 'undo':
            product_id = request.json.get('product_id')
            collect_info = db.session.query(Collect).filter(Collect.collect_user == user.id,
                                                            Collect.collect_product == product_id).first()
            if collect_info:
                db.session.delete(collect_info)
                db.session.commit()
                ret = {
                    'errno': 0,
                    'errmsg': '取消收藏成功'
                }

            else:
                ret = {
                    'errno': 6009,
                    'errmsg': '没有查询到您收藏该商品'
                }
            return jsonify(ret)
    else:
        return redirect(url_for('index.index'))


@user_bp.route('/user_head')
def user_head():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    return render_template('user_head.html', user=user)


@user_bp.route('/user_avatar', methods=['POST'])
def user_avatar():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if user.avatar_url:
        db_avatar_url = user.avatar_url
        qiniu_url = "http://qiys2x29i.hn-bkt.clouddn.com/"
        if qiniu_url in db_avatar_url:
            db_avatar_url = db_avatar_url.replace(qiniu_url, "")
            url = './static/user_head/' + db_avatar_url
            os.remove(url)
    # 生成图片随机名称
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    # 获取前端上传的图片
    img = request.files.get('avatar')
    # print('当前绝对路径=========',BASEDIR)
    # 存放图片的路径
    path = './static/user_head/'
    imgName = ran_str + img.filename
    file_path = path + imgName
    img.save(file_path)
    qiniu_avatar_url = upload_image_to_qiniu(file_path, imgName)
    user.avatar_url = qiniu_avatar_url
    db.session.commit()
    ret = {
        'errno': 0,
        'errmsg': '成功'
    }
    return jsonify(ret)
